package com.mlc.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.mlc.core.dto.RequestDto;
import com.mlc.core.service.UsersService;
import com.mlc.data.entity.Users;
import com.mlc.utils.commom.ResponseResult;
import com.mlc.utils.enums.CodeType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author FireWang
 * @date 2022/03/14 02:43:39
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/user")
public class UsersController {
    private UsersService usersService;
    private static JSONObject result;

    /**
     * 微信小程序注册
     *
     * @param loginDto 注册信息参数
     * @return
     */
    @PostMapping("/login")
    public JSONObject register(@RequestBody RequestDto loginDto) {
        log.info("用户登录：" + loginDto);
        try {
            //判断用户是否存在
            Users user = usersService.exist(loginDto);
            if (user == null) {
                user = usersService.insert(loginDto);
            }

            //增加登录次数
            user.setLoginTimes(user.getLoginTimes() + 1);
            usersService.update(user);

            result = ResponseResult.build(CodeType.SUCCESS, "成功！");
            result.put("user", user);
        } catch (Exception e) {
            log.error("用户登录失败：" + e.getMessage());
            result = ResponseResult.build(CodeType.FAIL, "失败：" + e.getMessage());
        }
        return result;
    }

}